package com.woniu.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson2.JSONObject;
import java.util.Base64;

public class XunfeiTranslationUtil {
    private static final String APP_ID = "YOUR_APP_ID";
    private static final String API_KEY = "YOUR_API_KEY";
    private static final String TRANSLATE_URL = "https://itrans.xfyun.cn/v2/its";

    public static String translateAudio(byte[] audioData, String fromLang, String toLang) throws Exception {
        // 1. Base64编码音频
        String audioBase64 = Base64.getEncoder().encodeToString(audioData);

        // 2. 构造请求体
        JSONObject businessParams = new JSONObject();
        businessParams.put("from", fromLang); // 源语言，如"en"
        businessParams.put("to", toLang);     // 目标语言，如"zh"

        JSONObject requestData = new JSONObject();
        requestData.put("business", businessParams);
        requestData.put("data", audioBase64);
        requestData.put("common", new JSONObject().fluentPut("app_id", APP_ID));

        // 3. 发送HTTP请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(TRANSLATE_URL);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("X-CurTime", String.valueOf(System.currentTimeMillis() / 1000));
        httpPost.setHeader("X-Param", Base64.getEncoder().encodeToString(businessParams.toString().getBytes()));
        // 计算签名（API_KEY + X-CurTime + X-Param）
        String sign = calculateSign(API_KEY, httpPost.getFirstHeader("X-CurTime").getValue(),
                httpPost.getFirstHeader("X-Param").getValue());
        httpPost.setHeader("X-CheckSum", sign);
        httpPost.setEntity(new StringEntity(requestData.toString()));

        HttpResponse response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        return parseTranslationResult(result); // 解析翻译结果
    }

    private static String calculateSign(String apiKey, String curTime, String param) {
        // 实际实现需按讯飞文档生成MD5签名
        return DigestUtils.md5Hex(apiKey + curTime + param);
    }

    private static String parseTranslationResult(String jsonResult) {
        JSONObject result = JSONObject.parseObject(jsonResult);
        return result.getJSONObject("data").getString("result");
    }
}